var chapterContentCKEditor;

function getChapterContentId(){
    return document.getElementById('formInputContentId').value;
}

class Xin880UploadAdapter {
    constructor(loader) {
        // The file loader instance to use during the upload.
        this.loader = loader;
    }

    // Starts the upload process.
    upload() {
        return this.loader.file
            .then(file => new Promise((resolve, reject) => {
                this.uploadFile(file, resolve);
            }));
    }

    uploadFile(file, resolve) {
        // 我们通过formData进行图片上传
        let form = new FormData();
        form.append('upload', file);
        // 上传文件
        $.ajax({
            url: "/upload/images?chapterContentId="+getChapterContentId(),   /* 上传图片的后端接口 */
            type: 'POST',
            data: form,
            contentType: false,
            processData: false,
            beforeSend: function (request) {
                // request.setRequestHeader("Content-Type", file.type);
            },
            success: function (respJson) {
                if (respJson.msg.code == 0) {
                    resolve({
                        // default: respJson.result[0].url
                        default: respJson.msg.url
                    });
                } else {
                    alert("错误：" + respJson.msg)
                }
            },
            error: function (e) {
            }
        });
    }

    // Aborts the upload process.
    abort() {
        // Reject the promise returned from the upload() method.
        server.abortUpload();
    }
}

function creatCKEditor(){
    // 初始化editor
        ClassicEditor
        .create(document.querySelector( '#bookChapterCKEditor'),{
            toolbar: {
                items: [
                    'sourceEditing',
                    '|',
                    'undo',
                    'redo',
                    'findAndReplace',
                    '|',
                    'heading',
                    '|',
                    'fontFamily',
                    'fontSize',
                    'bold',
                    'italic',
                    'underline',
                    'fontColor',
                    'fontBackgroundColor',
                    'alignment',
                    'bulletedList',
                    'numberedList',
                    'todoList',
                    'highlight',
                    'superscript',
                    'subscript',
                    '|',
                    'link',
                    'code',
                    'codeBlock',
                    'htmlEmbed',
                    '|',
                    'imageUpload',
                    'imageInsert',
                    'mediaEmbed',
                    'insertTable',
                    '|',
                    'horizontalLine',
                    'outdent',
                    'indent',
                    'blockQuote',
                    'pageBreak',
                    'removeFormat',
                    'specialCharacters',
                    'restrictedEditingException',
                    'strikethrough',
                    '|',
                    'style',
                    'textPartLanguage',
                    '|',
                    'selectAll',
                    'showBlocks',
                    'ckfinder',
                    '|'
                ]
            },
            image: {
                toolbar: [
                    'imageTextAlternative',
                    'toggleImageCaption',
                    'imageStyle:inline',
                    'imageStyle:block',
                    'imageStyle:side',
                    'linkImage'
                ]
            },
            // ckfinder: {   /* 暂时没有想到动态方式 先注释掉此上传图片方式 */
            //     uploadUrl: "/upload/images?chapterContentId="+getChapterContentId(),   /* 上传图片的后端接口 */
            // },
            table: {
                contentToolbar: [
                    'tableColumn',
                    'tableRow',
                    'mergeTableCells',
                    'tableCellProperties',
                    'tableProperties'
                ]
            },
            list: {
                properties: {
                    styles: true,
                    startIndex: true,
                    reversed: true
                }
            },
            fontFamily: {
                options: [
                    'default',
                    '宋体',
                    '楷体',
                    '微软雅黑',
                    '黑体',
                    '隶书',
                ],
                supportAllValues: true
            },
            fontSize: {
                options: [ 6, 8, 10,12,14, 'default', 18, 20, 22, 24, 26, 32,48,60 ],
                supportAllValues: true
            },
            htmlSupport: {
                allow: [
                    {
                        name: /.*/,
                        attributes: true,
                        classes: true,
                        styles: true
                    }
                ]
            },
            // https://ckeditor.com/docs/ckeditor5/latest/features/link.html#custom-link-attributes-decorators
            link: {
                defaultProtocol: 'http://',
                decorators: {
                    // addTargetToExternalLinks: true,
                    addTargetToExternalLinks: {
                        mode: 'automatic',
                        callback: url => /^(https?:)?\/\//.test( url ),
                        attributes: {
                            target: '_blank',
                            rel: 'noopener noreferrer'
                        }
                    },
                    defaultProtocol: 'https://',
                    toggleDownloadable: {
                        mode: 'manual',
                        label: 'Downloadable',
                        attributes: {
                            download: 'file'
                        }
                    },
                    openInNewTab: {
                        mode: 'manual',
                        label: 'Open in a new tab',
                        attributes: {
                            target: '_blank',
                            rel: 'noopener noreferrer'
                        }
                    }
                }
            },
            mention: {
                feeds: [
                    {
                        marker: '@',
                        feed: [
                            '@apple', '@bears', '@brownie', '@cake', '@cake', '@candy', '@canes', '@chocolate', '@cookie', '@cotton', '@cream',
                            '@cupcake', '@danish', '@donut', '@dragée', '@fruitcake', '@gingerbread', '@gummi', '@ice', '@jelly-o',
                            '@liquorice', '@macaroon', '@marzipan', '@oat', '@pie', '@plum', '@pudding', '@sesame', '@snaps', '@soufflé',
                            '@sugar', '@sweet', '@topping', '@wafer'
                        ],
                        minimumCharacters: 1
                    }
                ]
            },
            removePlugins: [
                'AIAssistant',
                'CKBox',
            ],
            placeholder: '欢迎使用880文档管理系统!',
            language: 'zh-cn',
            licenseKey: '',


        })
        .then( editor => {
            editor.plugins.get("FileRepository").createUploadAdapter = loader => {
                return new Xin880UploadAdapter(loader);
            };






            chapterContentCKEditor = editor;
            editor.model.document.on('change:data', function () {
                $("#bookChapterCKEditor").val(editor.getData());
            });
            editor.model.document.on('mouseup',function(){
                console.log("mouseup....");
            });
            // 解决jquery validate校验失败问题






        } )
        .catch( err => {
            console.error( err.stack );
        } );
}
